package org.example.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
    //数据库连接的配置信息
    private static String driverClass = null;
    private static String url = null;
    private static String user = null;
    private static String password = null;
    /**
     * 使用静态代码块读取配置文件
     */
    static {
        try {
            //读取配置信息
            Properties properties = new Properties();
            properties.load(JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            //开始解析配置文件
            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            //加载驱动
            Class.forName(driverClass);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        //开始创建连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 管理数据库连接
     *
     * @param connection
     */
    private static void closeConnection(Connection connection) {
        //判断是否为null
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭Statement
     *
     * @param statement
     */
    private static void closeStatement(Statement statement) {
        //判断是否为null
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭结果集合
     *
     * @param resultSet
     */
    private static void closeResultSet(ResultSet resultSet) {
        //判断是否为null
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭数据库相关连接
     *
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        closeConnection(connection);
        closeStatement(statement);
        closeResultSet(resultSet);
    }

}
